import Taro from '@tarojs/taro';
import { setGlobalData } from './global_data';
import request from './request';
import { sleep } from '../utils';

export function getSystemInfo() { // 获取系统信息
  Taro.getSystemInfo({
    success: res => {
      var modelmes = res.model;
      let isIphoneX = 0;
      if (
        modelmes.search("iPhone X") > -1 ||
        modelmes.search("unknown") > -1 ||
        modelmes.search("iPhone12") > -1
      ) {
        isIphoneX = 1;
      }
      // 缓存到本地
      try {
        Taro.setStorage({ key: "isIphoneX", data: isIphoneX });
        Taro.setStorage({ key: "windowHeight", data: res.windowHeight });
        Taro.setStorage({ key: "windowWidth", data: res.windowWidth });
        Taro.setStorage({ key: "pixelRatio", data: res.pixelRatio });
        // 设置到全局数据对象
        setGlobalData('isIphoneX', isIphoneX);
        setGlobalData('windowHeight', res.windowHeight);
        setGlobalData('windowWidth', res.windowWidth);
        setGlobalData('pixelRatio', res.pixelRatio);
      } catch (error) {
        console.log(error);
      }
    }
  });
};

// 微信获取code
const wxLogin = (isNeedReLaunch, isNeedLogin) => {
  // 登录
  Taro.login({
    async success(res) {
      console.log(res.code);
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      // const result = await request({ url: api.login, data: { code: res.code } });
      await sleep(500);
      const result = { success: 1, token: 'test1234' };
      if (result.success) {
        // todo保存用户信息
        Taro.setStorageSync('token', result.token);
        // 跳转到首页
        isNeedReLaunch && Taro.reLaunch({ url: '/pages/index/index'});
        return ;
      }
      // 跳转到登录页面
      isNeedLogin && Taro.reLaunch({url: '/pages/login/index'});
    }
  });
}
export async function checkLogin(isNeedReLaunch, isNeedLogin){ // 判断是否登录(需要根据是否需要登录)
  // 本地token
  var token = Taro.getStorageSync("token");
  if (!token) {
    wxLogin(isNeedReLaunch, isNeedLogin);
    return;
  }
  // const result = request({ tartget: 'login' });
  await sleep(500);
  const result = { success: 1, token: 'test1234' };
  if (result.success) {
    // todo保存用户信息
    isNeedLogin && Taro.reLaunch({url: '/pages/index/index'});
    return;
  }
  // token已无效
  if (!result.success) {
    wxLogin(isNeedReLaunch, isNeedLogin);
  }
};

export function getUserWxInfo() {
  Taro.getSetting({
    success: res => {
      if (res.authSetting["scope.userInfo"]) {
        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        Taro.getUserInfo({
          success: userInfo => {
            request({ tartget: 'updateUserAvatar', data: { avatar: userInfo.avatarUrl } });
          }
        });
      }
    }
  });
};
